<template>
	<view>
		<view class="bgw wrapper">
			<view class="blank20"></view>
			<view class="flex">
				<view class="">
					<text class="text-light-gray">本月：</text>
					<text class="font-bold">{{month_cost_sales_dic.ratio | formatRatio}}</text>
				</view>
				<view class="flex-1 text-center">
					<text class="text-light-gray">本周：</text>
					<text class="font-bold">{{week_cost_sales_dic.ratio | formatRatio}}</text>
				</view>
				<view class="">
					<text class="text-light-gray">本日：</text>
					<text class="font-bold">{{day_cost_sales_dic.ratio | formatRatio}}</text>
				</view>
			</view>
			<view class="blank20"></view>
		</view>
		<view class="blank20"></view>
		<view class="bgw">
			<view class="flex wrapper">
				<view class="text-gray font-40">
					日期：
				</view>
				<view class="flex-1">
					<picker mode="date" :value="form.day" @change="bindDateChange">
						<view class="blank20"></view>
						<view class="flex">
							<view class="text-right flex-1  font-40 font-bold">
								{{form.day}}
							</view>
							<view class="ml5">
								<u-icon name="arrow-down" color="#999999" size="20"></u-icon>
							</view>
						</view>
						<view class="blank20"></view>
					</picker>
				</view>
			</view>
			<u-line></u-line>
			<view class="flex wrapper" v-if="cus_arr.length>0">
				<view class="text-gray font-40">
					客户：
				</view>
				<view class="flex-1">
					<picker @change="bindCusChange" :value="cus_index" :range="cus_arr" range-key="label">
						<view class="blank20"></view>
						<view class="flex">
							<view class="text-right flex-1 font-40 font-bold">
								{{cus_arr[cus_index].label || '请选择'}}
							</view>
							<view class="ml5">
								<u-icon name="arrow-down" color="#999999" size="20"></u-icon>
							</view>
						</view>
						<view class="blank20"></view>
					</picker>
				</view>
			</view>
			<u-line></u-line>
			<view class="flex wrapper" v-if="dinner_type_arr.length>0">
				<view class="text-gray font-40">
					餐别：
				</view>
				<view class="flex-1 flex" style="flex-wrap: wrap;padding: 10upx 0;">
					<view class="mr15" style="margin-top: 10upx;margin-bottom: 10upx;" v-for="(v, i) in dinner_type_arr"
						:key="i">
						<u-tag :text="v.label" :plain="dinner_type_index != i" type="primary" :name="i" size="large"
							@click="bindDinnerTypeChange(i)"></u-tag>
					</view>
				</view>
			</view>
		</view>
		<view class="blank20"></view>
		<view class="bgw wrapper">
			<!-- <view class="blank20"></view> -->
			<view class="flex">
				<view class="flex-1 flex">
					<text class="text-light-gray">快餐：</text>
					<u--input placeholder="0" border="bottom" type="number" v-model="dinner_qty"
						@blur="dinner_blur"></u--input>
				</view>
				<view class="flex-1 flex">
					<text class="text-light-gray">特色：</text>
					<u--input placeholder="0" border="bottom" type="number" v-model="dinner_qty_ts"
						@blur="dinner_blur"></u--input>
				</view>
				<view class="flex-1 flex">
					<text class="text-light-gray">餐标：</text>
					<u--input placeholder="0.00" border="bottom" type="number" v-model="dinner_price"
						@blur="dinner_blur"></u--input>
				</view>
				<view class="">
					<!-- <text class="text-light-gray">预计销售：</text> -->
					<text class="font-bold">￥{{dinner_sales|formatPrice}}</text>
				</view>
			</view>
			<view class="blank20"></view>
			<view class="flex">
				<view class="">
					<text class="text-light-gray">本餐菜品成本：</text>
					<text class="font-bold">￥{{dinner_cost | formatPrice}}</text>
				</view>
				<view class="flex-1 text-center">
					<text class="text-light-gray">菜品成本%：</text>
					<text class="font-bold">{{dinner_cost_ratio|formatPrice}}%</text>
				</view>
			</view>
			<view class="blank20"></view>
		</view>
		<view class="blank20"></view>

		<template v-for="(v,i) in list">
			<view class="bgw wrapper">
				<view class="flex">
					<view class="">
						<text class="font-bold font-40">{{v.dish_key_name}}</text>
						<text class="">【{{v.dish_top_category_name}} | {{v.sales_type == 'kuai'?'快餐':'特色'}}】</text>
					</view>
					<view class="flex-1">
						<view class="blank20"></view>
						<input style="font-size: 36upx;text-align: right;" class="font-bold" v-model="dish_qty[i]"
							type="number" placeholder="请输入" @input="qty_input" :data-index="i" />
						<view class="blank20"></view>
					</view>
				</view>
				<u-line></u-line>
				<view class="blank20"></view>
				<view class="flex">
					<view class="flex-1">
						<text class="text-light-gray">成本：</text>
						<text class="font-bold">￥{{v.dish_cost}}</text>
					</view>
					<view class="flex-1">
						<text class="text-light-gray">总成本：</text>
						<text class="font-bold">￥{{dish_total_cost[i] | formatPrice}}</text>
					</view>
				</view>
				<view class="blank20"></view>
			</view>
			<view class="blank20"></view>
		</template>
		<nodata v-if="loadingStatus == 'end' && list.length == 0"></nodata>

		<u-gap height="90"></u-gap>
		<cover-view class="fixed-bottom bgw" v-if="list.length != 0">
			<cover-view class="blank20"></cover-view>
			<cover-view class="wrapper">
				<cover-view class="flex">
					<cover-view class="flex-1">
						<cover-view class="reset-btn" @click="resetForm">重置</cover-view>
						<!-- <u-button type="info" class="" text="重置" @click="resetForm"></u-button> -->
					</cover-view>
					<cover-view class="ml15"></cover-view>
					<cover-view class="flex-1">
						<cover-view v-if="isChangeFlag" class="submit-btn" @click="submitForm">确定</cover-view>
						<cover-view v-if="!isChangeFlag" class="submit-btn submit-btn-disabled">确定</cover-view>
						<!-- <u-button type="success" text="确定" @click="submitForm"></u-button> -->
					</cover-view>
				</cover-view>
			</cover-view>
			<cover-view class="blank20"></cover-view>
		</cover-view>

	</view>
</template>

<script>
	import recorderBtn from "@/pagesA/components/recorder-btn/recorder-btn.vue";
	import nodata from '@/components/nodata.vue';
	import {
		plan_day_cus_dish_allocation,
		plan_day_save_cus_dish_allocation,
		plan_day_cus_dish_allocation_common_data,
		plan_day_save_cus_dinner_mode
	} from '@/common/api.js';

	function formatPrice(price) {
		price = '' + price;
		price = price
			.replace(/\s*/g, "") //去除字符串内所有的空格
			.replace(/[^\-\d.]/g, '') // 清除“-”“数字”和“.”以外的字符
			.replace(/\.{2,}/g, '.') // 只保留第一个. 清除多余的
			.replace('.', '$#$')
			.replace(/\./g, '')
			.replace('$#$', '.')
			.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3'); // 只能输入两个小数
		// if (price.indexOf('.') < 0 && price != '') {
		//     // 以上已经过滤，此处控制的是如果没有小数点，首位不能为类似于 01、02的金额
		//     price = parseFloat(price);
		// }
		// if (price[0] == '0' && price != '') {
		//     // 以上已经过滤，此处控制的是如果没有小数点，首位不能为类似于 01、02的金额
		//     price = parseFloat(price);
		// }
		if (price != '') {
			price = Number(price);
		}
		return price;
	};
	export default {
		components: {
			recorderBtn,
			nodata
		},
		data() {
			return {
				loadingStatus: '',
				dish_key_obj: null,
				dish_top_category_obj: null,
				role: null,
				userInfo: null,
				form: {
					day: '',
				},
				cus_index: 0,
				dinner_type_index: 0,
				allList: [],
				list: [],
				dish_qty: [], //份数
				dish_total_cost: [],
				day_cost_sales_dic: {},
				month_cost_sales_dic: {},
				week_cost_sales_dic: {},
				isChangeFlag: false,
				dinner_cost: 0,
				// dinner_cost_ratio: 0,
				dinner_price: 0,
				dinner_qty: 0,
				dinner_qty_ts: 0,
				// dinner_sales: 0,
				cus_arr: [],
				dinner_type_arr: [],
				dinner_mode: [],
				isSubmit:false
			}
		},
		filters: {
			formatRatio(ratio) {
				return formatPrice((ratio || 0) * 100) || 0 + '%'
			}
		},
		watch: {
			// dish_qty:{
			// 	handler(newVal, oldVal) {
			// 		// console.log(oldVal);
			// 		// let sum = 0;
			// 		let diff = 0;
			// 		this.dish_total_cost = newVal.map((v,i)=>{
			// 			let qty = Number(v)||0;
			// 			let num = qty * this.list[i].dish_cost;
			// 			let old_dish_qty = this.allList.find(d=>d.id == this.list[i].id).dish_qty;
			// 			if(qty-old_dish_qty != 0){
			// 				diff+=(qty-old_dish_qty)*this.list[i].dish_cost;
			// 			}
			// 			return num
			// 		});
			// 		if(diff){
			// 			this.updateRatio(diff);
			// 		}
			// 		// this.day_cost_sales_dic.ratio = sum;
			// 	},
			// 	immediate: false,
			// 	deep: true
			// }
		},
		computed: {
			dinner_sales() {
				try {
					return this.dinner_price * this.dinner_qty + this.dinner_price * this.dinner_qty_ts;
				} catch (e) {
					return 0
				}
			},
			dinner_cost_ratio() {
				try {
					return this.dinner_cost / this.dinner_sales * 100
				} catch (e) {
					return 0
				}
			},
			// cus_arr() {
			// 	let write_cus_loc = this.$store.getters.get_role['报表模块']['销售'].write;
			// 	let arr = write_cus_loc.map(v => {
			// 		return {
			// 			label: v[1],
			// 			id: v[0]
			// 		}
			// 	})
			// 	return arr
			// },
			// dinner_type_arr() {
			// 	let dinner_type_category = this.$store.getters.get_dinner_type_category;
			// 	// console.log(dinner_type_category);
			// 	let arr = dinner_type_category.map(v => {
			// 		return {
			// 			label: v.name,
			// 			id: v.id,
			// 			dinner_type: v.dinner_type
			// 		}
			// 	})
			// 	return arr
			// },
		},
		methods: {
			dinner_blur() {
				this.isChangeFlag = true;
				this.dinner_price = this.formatPrice(Number(this.dinner_price));
				this.dinner_qty = this.formatPrice(Number(this.dinner_qty));
				this.dinner_qty_ts = this.formatPrice(Number(this.dinner_qty_ts));
			},
			qty_input(e) {
				this.isChangeFlag = true;
				let index = e.target.dataset.index;
				if (this.dish_qty[index] + '' != '') {
					let num = Number(this.dish_qty[index]);
					this.$set(this.dish_qty, index, num);
				};
				let diff = this.update_dish_total_cost();
				this.updateRatio(diff || 0);
			},
			update_dish_total_cost() {
				let diff = 0;
				let dinner_cost = 0;
				this.dish_total_cost = this.dish_qty.map((v, i) => {
					let qty = Number(v) || 0;
					let num = qty * this.list[i].dish_cost;
					let old_dish_qty = this.list[i].dish_qty;
					if (qty - old_dish_qty != 0) {
						diff += (qty - old_dish_qty) * this.list[i].dish_cost;
					}
					dinner_cost += num;
					return num
				});
				this.dinner_cost = dinner_cost;
				return diff
			},
			updateRatio(diff) {
				// console.log(diff);
				try {
					let day_cost = this.day_cost_sales_dic.cost + diff;
					this.day_cost_sales_dic.ratio = day_cost / this.day_cost_sales_dic.sales || 0;
					let month_cost = this.month_cost_sales_dic.cost + diff;
					this.month_cost_sales_dic.ratio = month_cost / this.month_cost_sales_dic.sales||0;
					let week_cost = this.week_cost_sales_dic.cost + diff;
					this.week_cost_sales_dic.ratio = week_cost / this.week_cost_sales_dic.sales ||0;
				} catch (e) {
					//TODO handle the exception
				}

			},
			async save_cus_dinner_mode(){
				let dinner_type_id = this.dinner_type_arr[this.dinner_type_index].id;
				let cus_loc_id = this.cus_arr[this.cus_index].id;
				let dinner_mode = this.dinner_mode.find(v => v.dinner_type_id == dinner_type_id && v.cus_loc_id == cus_loc_id);
				let vals = {
					id:dinner_mode.id,
					price:this.dinner_price||0,
					dinner_qty_upper_limit_kc:this.dinner_qty||0,
					dinner_qty_upper_limit_ts:this.dinner_qty_ts||0,
				};
				vals.price = Number(vals.price);
				vals.dinner_qty_upper_limit_kc = Number(vals.dinner_qty_upper_limit_kc);
				vals.dinner_qty_upper_limit_ts = Number(vals.dinner_qty_upper_limit_ts);
				await plan_day_save_cus_dinner_mode({
					vals_list: [vals]
				}).then(res => {
				
				})
			},
			async submitForm() {
				if(!this.getIsSubmit()){
					uni.$u.toast('修改时间已过!');
					return;
				}
				let _this = this;
				uni.showLoading({
					title: "加载中",
				});
				await this.save_cus_dinner_mode();
				let list = this.list.map((v, i) => {
					let {
						cus_loc_id,
						id
					} = v;
					let item = {
						id,
						cus_loc_id,
						dish_qty: Number(_this.dish_qty[i]) || 0,
					};
					return item;
				});
				plan_day_save_cus_dish_allocation({
					vals_list: list
				}).then(async(res) => {
					uni.$u.toast('修改成功');
					await this.get_common_data();
					this.getData();
				}).catch((res) => {

				}).finally(() => {
					uni.hideLoading();
					uni.stopPullDownRefresh();
				})
			},
			async bindDateChange(e) {
				if (this.form.day != e.detail.value) {
					this.form.day = e.detail.value;
					await this.get_common_data();
					this.getData();
				}
			},
			bindCusChange(e) {
				let index = e.detail.value;
				if (this.cus_index != index) {
					this.cus_index = index;
					this.getData();
				}
			},
			bindDinnerTypeChange(index) {
				if (this.dinner_type_index != index) {
					this.dinner_type_index = index;
					this.getData();
				}
			},
			setList() {
				let dinner_type_id = this.dinner_type_arr[this.dinner_type_index].id;
				this.list = this.allList.filter(v => v.dinner_type_id == dinner_type_id);
				this.dish_qty = this.list.map(v => v.dish_qty);
				this.update_dish_total_cost();
			},
			resetForm() {
				// console.log(this.dinner_type_arr);
				this.form.day = this.today_year_month_day;
				this.cus_index = 0;
				let default_dinner_type_index = this.dinner_type_arr.findIndex(v => v.label == '中餐');
				if (default_dinner_type_index == -1) {
					default_dinner_type_index = 0;
				}
				this.dinner_type_index = default_dinner_type_index;
				this.getData();
			},
			getData() {
				// 清空旧数据
				this.dish_total_cost = 0;
				this.day_cost_sales_dic = {};
				this.month_cost_sales_dic = {};
				this.week_cost_sales_dic = {};
				this.list = [];
				this.dish_qty = [];
				this.update_dish_total_cost();

				let dinner_type_id = this.dinner_type_arr[this.dinner_type_index].id;
				let cus_loc_id = this.cus_arr[this.cus_index].id;
				try {
					let dinner_mode = this.dinner_mode.find(v => v.dinner_type_id == dinner_type_id && v.cus_loc_id ==
						cus_loc_id);
					this.dinner_price = dinner_mode.price;
					this.dinner_qty = dinner_mode.dinner_qty_upper_limit_kc;
					this.dinner_qty_ts = dinner_mode.dinner_qty_upper_limit_ts;
				} catch (e) {
					this.dinner_price = 0;
					this.dinner_qty = 0;
					this.dinner_qty_ts = 0;
				}

				uni.showLoading({
					title: '加载中'
				});
				this.loadingStatus = 'loading';
				let day = this.form.day;

				let data = {
					day,
					dinner_type_id,
					cus_loc_id
					// day:'2024-03-31',
					// dinner_type_id:110,
					// cus_loc_id:4229
				};
				plan_day_cus_dish_allocation(data).then((res) => {
					let {
						day_cost_sales_dic,
						month_cost_sales_dic,
						plan_day_cus_dish_qty,
						week_cost_sales_dic
					} = res.result;
					let list = [];
					plan_day_cus_dish_qty.forEach((v, i) => {
						v.dish_top_category_name = this.dish_top_category_obj[v.dish_top_category_id]
							.name_cn;
						v.dish_key_name = this.dish_key_obj[v.dish_key_id].name;
						v.cus_loc_id = cus_loc_id;
						list.push(v);
					});
					// this.allList = plan_day_cus_dish_qty;
					this.day_cost_sales_dic = day_cost_sales_dic;
					this.month_cost_sales_dic = month_cost_sales_dic;
					this.week_cost_sales_dic = week_cost_sales_dic;
					this.list = list;
					this.dish_qty = this.list.map(v => v.dish_qty);
					this.update_dish_total_cost();
					this.isChangeFlag = false;
					// this.setList();
				}).catch(() => {}).finally(() => {
					this.loadingStatus = 'end';
					uni.hideLoading();
					uni.stopPullDownRefresh();
				})
			},
			async get_common_data() {
				uni.showLoading({
					title: '加载中'
				});
				this.loadingStatus = 'loading';
				let day = this.form.day;
				await plan_day_cus_dish_allocation_common_data({
					day
				}).then((res) => {
					let {
						dinner_type_category,
						dinner_mode,
						cus_lst,
						dish_key_lst,
						dish_top_category,
						dead_line_date,
						dead_line_time
					} = res.result;
					this.cus_arr = cus_lst.map(v => {
						return {
							label: v.name,
							id: v.cus_loc_id
						}
					});
					this.dinner_type_arr = dinner_type_category.map(v => {
						return {
							label: v.name,
							id: v.id,
							dinner_type: v.dinner_type
						}
					});
					this.dish_key_obj = this.toObj(dish_key_lst, 'id');
					this.dish_top_category_obj = this.toObj(dish_top_category, 'id');
					this.dinner_mode = dinner_mode;
					this.dead_line_time = dead_line_time;
					this.dead_line_date = dead_line_date;
					// this.isSubmit = this.getIsSubmit();
					// console.log(this.isSubmit);
				})
			},
			getIsSubmit(){
				// console.log(this.dead_line_date);
				let dead_line_date = this.dead_line_date;
				let dead_line_time = this.dead_line_time;
				let day = this.form.day;
				let flag = false;
				if(dead_line_date && dead_line_time){
					let d_date_str;
					if(dead_line_date == 'this_Monday'){
						d_date_str = this.getLastDay(day,1);
					}
					if(dead_line_date == 'this_Tuesday'){
						d_date_str = this.getLastDay(day,2);
					}
					if(dead_line_date == 'this_Wednesday'){
						d_date_str = this.getLastDay(day,3);
					}
					if(dead_line_date == 'this_Thursday'){
						d_date_str = this.getLastDay(day,4);
					}
					if(dead_line_date == 'this_Friday'){
						d_date_str = this.getLastDay(day,5);
					}
					if(dead_line_date == 'this_Saturday'){
						d_date_str = this.getLastDay(day,6);
					}
					if(dead_line_date == 'this_Sunday'){
						d_date_str = this.getLastDay(day,0);
					}
					if(dead_line_date == 'two_days_ahead'){
						d_date_str = this.getAheadDay(day,2);
					}
					if(d_date_str){
						d_date_str += ' '+dead_line_time;
						// console.log(d_date_str);
						let d_date = new Date(d_date_str);
						let now_date = new Date();
						if(d_date.getTime()>now_date.getTime()){
							flag = true;
						}
					}
				}
				// console.log(flag);
				return flag
			},
			// 获取几天前
			getAheadDay(date_str,num){
				const today = new Date(date_str);
				today.setDate(today.getDate() - 2);
				const year = today.getFullYear();
				const month = today.getMonth() + 1; // 月份是从0开始的
				const day = today.getDate();
				// 格式化日期为YYYY-MM-DD
				return `${year}-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')}`;
			},
			// 获取上周几  num == 0周日
			getLastDay(date_str,num) {
			  const today = new Date(date_str);
			  let friday;
			 
			  // 如果今天是周五，则获取上个周五
			  if (today.getDay() === num) {
			    friday = new Date(today);
			    friday.setDate(today.getDate() - 7);
			  } else if(num > today.getDay()){
				  friday = new Date(today);
				  friday.setDate(today.getDate() - (today.getDay() + (7-num)) % 7);
			  }else {
			    // 如果今天不是周五，则获取今天所在周的上个周五
			    friday = new Date(today);
			    friday.setDate(today.getDate() - (today.getDay() + (7-num)) % 7 - 7);
			  }
			 
			  const year = friday.getFullYear();
			  const month = friday.getMonth() + 1; // 月份是从0开始的
			  const day = friday.getDate();
			 
			  // 格式化日期为YYYY-MM-DD
			  return `${year}-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')}`;
			}
		},
		onShow() {
			try {
				// console.log();
				this.role = this.$store.getters.get_role;
				this.userInfo = this.$store.getters.get_userInfo;
				// this.dish_key_obj = this.$store.getters.get_dish_key_obj;
				// this.dish_top_category_obj = this.$store.getters.get_dish_top_category_obj;
			} catch (e) {
				uni.reLaunch({
					url: '/pages/login/login'
				});
			}
		},
		async onLoad(d) {
			// this.list = [{
			// 		name: '雪菜肉丝'
			// 	},
			// 	{
			// 		name: '雪菜肉丝'
			// 	},
			// 	{
			// 		name: '雪菜肉丝'
			// 	},
			// ];
			// this.fileList = [];
			// this.location = [];
			// this.consumed = [];
			// this.list.forEach((v,i)=>{
			// 	this.fileList.push([]);
			// 	this.location.push('');
			// 	this.consumed.push('');
			// });
			this.form.day = this.today_year_month_day;
			await this.get_common_data();
			this.resetForm();
		}

	}
</script>

<style>
	.fixed-bottom {
		border-top: 1px solid #ebedf0;
		z-index: 9999;
	}

	.reset-btn {
		color: #323233;
		background-color: #fff;
		border-radius: 3px;
		border: 1px solid #ebedf0;
		height: 40px;
		line-height: 40px;
		text-align: center;
	}

	.submit-btn {
		color: #ffffff;
		background-color: #5ac725;
		border-radius: 3px;
		border: 1px solid #5ac725;
		height: 40px;
		line-height: 40px;
		text-align: center;
	}

	.submit-btn-disabled {
		opacity: 0.6;
		background-color: #999;
		border: 1px solid #999;
	}
</style>